﻿using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using Zhao.Common.Helper;
using Zhao.IServer.Field;
using Zhao.IServer.Management_Arena;
using Zhao.Models.DTO;
using Zhao.Models.Entity;

namespace Zhao.Arena.Controllers.Management_Arena
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class VenuesController : ControllerBase
    {
        private readonly IMapper _mapper;
        private readonly IFieldTypesServer _typeServer;
        private readonly IFieldsServer _fieldsServer;
        private readonly IVenuesServer _venuesServer;
        private readonly IVenuesImageService _venuesImageService;


        public VenuesController(IMapper mapper, IFieldTypesServer typeServer, IFieldsServer fieldsServer, IVenuesServer venuesServer, IVenuesImageService venuesImageService)
        {
            this._mapper = mapper;
            this._typeServer = typeServer;
            this._fieldsServer = fieldsServer;
            this._venuesServer = venuesServer;
            this._venuesImageService = venuesImageService;
        }

        /// <summary>
        /// 获取球馆营业时间
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<JsonResult> GetBusiness()
        {
            var result = new ApiResult<VenuesTimeDto>() { Success = false, Message = "操作失败" };

            string? venueIdClaim = User.FindFirst("VenueId").Value;

            if (venueIdClaim == null || !Guid.TryParse(venueIdClaim, out Guid venueId))
            {
                result.Message = "对当前场地没有操作权限";
                return new JsonResult(result);
            }

            Expressionable<Venues> expressionable = new Expressionable<Venues>();

            expressionable.And(a => a.VenueID == venueId);

            var data =await _venuesServer.QueryAsync(expressionable.ToExpression());

            if (data != null)
            {
                result.Data = new VenuesTimeDto
                {
                    OpenTime = data.OpenTime,
                    CloseTime = data.CloseTime,
                };
                result.Success = true;
                result.Message = "操作成功";
            }

            return new JsonResult(result);

        }


        /// <summary>
        /// 获取球馆的Id和名字
        /// 提供给下拉框使用
        /// </summary>
        /// <param name="searchaString"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("DropdownOptions")]
        [Route("DropdownOptions/{searchaString}")]
        public async Task<JsonResult> GetDropdownOptions(string? searchaString = null)
        {
            var resule = new ApiResult<List<VenusInfo>>() { Success = true, Message = "查询成功" };

            Expressionable<Venues> expressionable = new Expressionable<Venues>();

            expressionable.AndIF(!searchaString.IsNullOrWhiteSpace(), x => x.VenueName.Contains(searchaString));

            var data = await _venuesServer.QueryListAsync(expressionable.ToExpression());

            resule.Data=_mapper.Map<List<VenusInfo>>(data);

            return new JsonResult(resule);
        }


        /// <summary>
        /// 获取球馆详情信息
        /// </summary>
        /// <param name="pageindex"></param>
        /// <param name="pageSize"></param>
        /// <param name="searchaString"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("{pageindex:int}/{pageSize:int}")]
        [Route("{pageindex:int}/{pageSize:int}/{searchaString}")]
        public async Task<JsonResult> GetVenuesPageInfo(int pageindex = 1, int pageSize = 10, string? searchaString = null)
        {
            var result = new PageModel<VenueDto>();
            Expressionable<Venues, Area, Area, Area> expressionable = new Expressionable<Venues,Area, Area, Area>();

            expressionable.AndIF(!searchaString.IsNullOrEmpty(), (a,b,c,d) => a.VenueName.Contains(searchaString) || a.Address.Contains(searchaString) || a.ManagerName.Contains(searchaString)|| b.Name.Contains(searchaString)|| c.Name.Contains(searchaString)|| d.Name.Contains(searchaString));

            result = await _venuesServer.GetVenuesPage(expressionable.ToExpression(),pageindex, pageSize);

            if (result != null)
            {
                return new JsonResult(result);
            }
            return new JsonResult(result);

        }


        /// <summary>
        /// 修改球馆信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<JsonResult> UpdateVenus([FromBody] VenueDto dto)
        {
            var result = new ApiResult
            {
                Success = false,
                Message = "修改失败"
            };

            try
            {
                // 1. 验证传入的DTO
                if (dto == null || dto.VenueId == Guid.Empty)
                {
                    result.Message = "参数无效";
                    return new JsonResult(result);
                }

                // 2. 检查球馆是否存在
                var existingVenue = await _venuesServer.QueryAsync(dto.VenueId);
                if (existingVenue == null)
                {
                    result.Message = "未找到指定的球馆";
                    return new JsonResult(result);
                }

                // 3. 将DTO映射到实体
                var venueToUpdate = new Venues
                {
                    VenueID = dto.VenueId,
                    VenueName = dto.VenueName,
                    Address = dto.Address,
                    Images = dto.Image,
                    ContactPhone = dto.ContactPhone,
                    Description = dto.Description,
                    IsDeleted = dto.Status,
                    CreatedAt = existingVenue.CreatedAt, // 保持原创建时间不变
                    UpdatedAt = DateTime.Now, // 更新修改时间
                    OpenTime = TimeSpan.Parse(dto.OpenTime),
                    CloseTime = TimeSpan.Parse(dto.CloseTime),
                    Phone = dto.phone,
                    ManagerName = dto.managerName,
                    Province=dto.provinceId,
                    City=dto.cityId,
                    Zone=dto.districtId,
                    ReservationRules=dto.rRules,
                    License=dto.LicenseImage
                };

                // 4. 更新数据库
                var updateResult = await _venuesServer.UpdateAsync(venueToUpdate);

                if (updateResult)
                {
                    result.Success = true;
                    result.Message = "修改成功";
                }
                else
                {
                    result.Message = "更新数据库失败";
                }
            }
            catch (FormatException ex)
            {
                result.Message = "时间格式不正确，请使用HH:mm格式";
            }
            catch (Exception ex)
            {
                result.Message = $"发生错误: {ex.Message}";
            }

            return new JsonResult(result);
        }

        /// <summary>
        /// 根据guid获取对应球馆的详情图片
        /// </summary>
        /// <param name="veunid"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("GeiImagsInfo/{veunid}")]
        public async Task<JsonResult> GeiImagsInfo(Guid veunid)
        {
            var result = new ApiResult<List<VenusImageDto>> { Success = false, Message = "操作失败" };

            if (veunid == default)
            {
                result.Message = "参数无效";
                return new JsonResult(result);  
            }

            //查询当前球馆是否存在
            var venu =await _venuesServer.QueryAsync(x => x.VenueID == veunid);

            if (venu == null)
            {
                result.Message = "球馆不存在";
                return new JsonResult(result);
            }

            var data = await _venuesImageService.QueryListAsync(x => x.VenueId == veunid);

           
            result.Data=_mapper.Map<List<VenusImageDto>>(data);

            result.Success = true;
            result.Message = "查询成功";

            return new JsonResult(result);
        }

        /// <summary>
        /// 根据guid获取对应球馆的详情信息
        /// </summary>
        /// <param name="veunid"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("GeVenueInfo/{veunid}")]
        public async Task<JsonResult> GeVenueInfo(Guid veunid)
        {
            var result = new ApiResult<VenueDto> { Success = false, Message = "操作失败" };

            if (veunid == default)
            {
                result.Message = "参数无效";
                return new JsonResult(result);
            }

            //查询当前球馆是否存在
            var venu = await _venuesServer.QueryAsync(x => x.VenueID == veunid);

            if (venu == null)
            {
                result.Message = "球馆不存在";
                return new JsonResult(result);
            }


            result.Data = _mapper.Map<Venues,VenueDto>(venu);

            result.Success = true;
            result.Message = "查询成功";

            return new JsonResult(result);
        }

        /// <summary>
        /// 修改商家详情图片
        /// </summary>
        /// <param name="images"></param>
        /// <returns></returns>
        [HttpPut("UpdateVImage")]
        public async Task<JsonResult> UpdateVImage([FromBody] VenunImages images)
        {
            var result = new ApiResult
            {
                Success=false,
                Message="操作失败"
            };

            if (images.Images.Count > 9)
            {
                result.Message = "最多上传九张图";
                return new JsonResult(result);
            }

            if (images.Id == default)
            {
                result.Message = "无效编号";
                return new JsonResult(result);
            }

            //查询球馆是否存在
           var venun=await _venuesServer.QueryAsync(x => x.VenueID == images.Id);

            if (venun == null)
            {
                result.Message = "球馆不存在";
                return new JsonResult(result);
            }

            //然后就传递给服务层
            var addInfo = _mapper.Map<List<VenuesImage>>(images.Images);

            addInfo.ForEach(x => x.VenueId = images.Id);

            if (await _venuesImageService.UpdateImage(images.Id, addInfo))
            {
                result.Message = "成功";
                result.Success = true;
                return new JsonResult(result);
            }

            return new JsonResult(result);
        }
    }
}
